<script setup>
import { reactive, ref, watch } from 'vue'
import { userRegisterService, userLoginService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

// 表单校验相关
//   1、el-from => :model="formModel"     绑定的整个formModel数据对象  （1和2对象里的内容是对应的）

const formModel = reactive({
  name: '',
  password: '',
  repassword: ''
})
//   2、el-from => :rules="rules"           绑定的整个rules规格对象   （1和2对象里的内容是对应的）
const rules = {
  // (1) 非空校验  required: true |  message 消息提示(通用)  |  trigger值 blur(失焦的时候验证)  change(状态发生改变的时候验证)(通用)
  // (2)长度校验  min:number, max:number
  // (3)正则校验  pattern:正则规则   \S 非空字符
  // (4)自定义校验 => 自己写逻辑校验(校验函数)
  //  validator:(rule,vaule,callback)
  //    -rule  当前校验规则相关的信息
  //    -vaule  所校验的表单元素目前的表单值
  //    -callback  无论成功或是失败,都需要callbackh回调
  //    --callback()  校验成功
  //    --callback(new Error(错误信息))  校验失败
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 12, message: '用户名必须是5-12位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur' }
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur' },
    {
      validator: (rule, vaule, callback) => {
        if (vaule !== formModel.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
//   3、表单元素 => v-model="ruleForm.xxx"   给表单元素，绑定form的子属性
//   4、el-form-item => prop配置生效的是哪个校验规则（和rules中的字段要对应）

// 预校验(注册)
const form = ref()
const register = async () => {
  // 注册成功之前,先进行校验,校验成功->请求,校验失败->提示
  await form.value.validate()
  await userRegisterService(formModel)
  ElMessage.success('注册成功')
  xian.value = true
}

const userStore = useUserStore()
const router = useRouter()
// 预检验(登录)
const login = async () => {
  await form.value.validate()
  const res = await userLoginService(formModel)
  ElMessage.success('登录成功')
  // 调用pinia持久化并传入token
  userStore.setToken(res.data.token)
  router.push('/layout')
}

const xian = ref(true)
// 登录注册切换的时候清空表单信息  (如果是用ref定义的数据可以直接修改整个对象)
watch(xian, () => {
  formModel.name = ''
  formModel.password = ''
  formModel.repassword = ''
})

// 记住密码
const rememberPassword = ref(false)
</script>
<template>
  <div class="login" v-if="xian">
    <el-form label-width="auto" ref="form" :model="formModel" :rules="rules" style="width: 400px">
      <el-form-item prop="name">
        <el-input placeholder="请输入账号" v-model="formModel.name" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input placeholder="请输入密码" v-model="formModel.password" />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="rememberPassword"> 记住密码 </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
    <p @click="xian = false">注册(点击跳转到注册页面)</p>
  </div>
  <div class="SignIn" v-else>
    <el-form label-width="auto" ref="form" :model="formModel" :rules="rules" style="width: 400px">
      <el-form-item prop="name">
        <el-input placeholder="请输入账号" v-model="formModel.name" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="formModel.password" />
      </el-form-item>
      <el-form-item prop="repassword">
        <el-input type="password" placeholder="请输入密码" v-model="formModel.repassword" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="register">注册</el-button>
      </el-form-item>
    </el-form>
    <p @click="xian = true">登录（点击跳转到登录页面）</p>
  </div>
</template>
